package com.company.beauty.nasa.elasticsearch.config;

import com.company.nuwa.common.enumration.GlobalCallbackEnum;
import com.company.nuwa.common.utils.JsonUtils;
import com.company.nuwa.common.utils.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.client.erhlc.ElasticsearchRestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>客户端配置</p>
 *
 * @author Lionel Lee
 * @version 1.0: ElasticsearchRestClient.java
 * @date 2021/6/28 2:23 下午
 */
@Slf4j
@Import(ElasticsearchProperties.class)
@Configuration
public class ElasticsearchConfig implements InitializingBean {

    @Autowired
    private ElasticsearchProperties elasticsearchProperties;

    @Bean(name = "highLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        RestClientBuilder builder = RestClient
                .builder(Objects.requireNonNull(makeHttpHost(elasticsearchProperties)));
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword()));
        builder
                .setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
    }

    @Bean
    public ElasticsearchRestTemplate restTemplate() {
        return new ElasticsearchRestTemplate(restHighLevelClient());
    }

    private HttpHost[] makeHttpHost(ElasticsearchProperties elasticsearchProperties) {
        log.info("[elasticsearchProperties]:{}", JsonUtils.objectToJson(elasticsearchProperties));
        Preconditions.checkArgument(StringUtils.isNotBlank(elasticsearchProperties.getEndpoints()),
                GlobalCallbackEnum.BAD_REQUEST.getCode(), "elasticsearch地址为空");
        String[] endpointArr = elasticsearchProperties.getEndpoints().split(",");
        List<HttpHost> httpHosts = new ArrayList<>();
        for (String s : endpointArr) {
            String[] address = s.split(":");
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            HttpHost httpHost = new HttpHost(ip, port, "http");
            httpHosts.add(httpHost);
        }
        log.info("[httpHosts]:{}", JsonUtils.objectToJson(httpHosts));
        return httpHosts.toArray(new HttpHost[httpHosts.size()]);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}